import axios, { AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig } from 'axios'
import { ElLoading } from 'element-plus'

const instance: AxiosInstance = axios.create({
  baseURL: 'https://mock.apifox.cn/m1/1689761-0-default',
  timeout: 5000
})

instance.interceptors.request.use(
  (config: AxiosRequestConfig): any => {
    return config
  },
  (error: AxiosError) => {
    console.log(error)
    return Promise.reject()
  }
)

instance.interceptors.response.use(
  (response: AxiosResponse): any => {
    if (response.status === 200) {
      return response.data
    } else {
      Promise.reject()
    }
  },
  (error: AxiosError) => {
    console.log(error)
    return Promise.reject()
  }
)

interface responseType extends AxiosResponse {
  code?: number
  message?: string
}

const fetch = (
  url: string,
  method = 'POST',
  params?: any,
  formData?: boolean,
  config?: object
): Promise<responseType> => {
  const loading = ElLoading.service({
    lock: true,
    text: '拼命加载中。。。',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const isPost = method === 'POST'
  const headers = {
    token: localStorage.getItem('token'),
    'Content-Type': formData ? 'multipart/form-data' : 'application/json'
  }
  return new Promise((resolve, reject) => {
    instance({
      url,
      method,
      params: isPost ? '' : params,
      data: isPost ? params : {},
      headers: headers,
      ...config
    })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject({ requestUrl: url, resErr: err })
      })
      .finally(() => [loading.close()])
  })
}

export default fetch
